package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.TaskDao;
import com.wlhse.dto.inDto.TaskManagementDto;
import com.wlhse.entity.Mail;
import com.wlhse.entity.TaskCheckPersonsPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.TaskManageService;
import com.wlhse.util.*;
import com.wlhse.util.state_code.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TaskManageServiceImpl implements TaskManageService {

    @Resource
    private TaskDao taskDao;

    @Resource
    private TaskManagementDto taskManagementDto;

    @Resource
    private ToPinyin toPinyin;

    @Resource
    private SortCodeUtil sortCodeUtil;

    @Resource
    private TaskCheckPersonsPojo taskCheckPersonsPojo;

    @Resource
    private SendMessageUtil sendMessageUtil;

    @Resource
    private GetNamesUtil getNamesUtil;

    @Resource
    private UseCountUtil useCountUtil;

    @Value("${RESOURCES_URL}")
    private String url;

    @Override
    @Transactional
    public String addTask(TaskManagementDto taskManagementDto) {
        //设置使用频率
        String redisName = "user_" + taskManagementDto.getPublisherID() + "_employee_task_management";
        String leaderIDs = taskManagementDto.getLeaderIDs();
        String[] leaderID = leaderIDs.split(",");
        for (String aLeaderID : leaderID) {
            useCountUtil.useCountSetCache(redisName, Integer.parseInt(aLeaderID));
        }

        int hashCode = taskManagementDto.hashCode();
        if (taskDao.queryTaskCount(hashCode) > 0)
            return NR.r(CodeDict.PROBLEM_TASK_SAME, 0, CodeDict.INSERT_FAILE, null, null, 0, 0);

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String time = df.format(new Date());
        taskManagementDto.setIssueDate(time);
        String company = null;
        String checkRank = taskManagementDto.getCheckRank();
        //.......
        switch (checkRank) {
            case "公司级":
                company = "A";
                break;
            case "分公司级":
                company = "B";
                break;
            case "基层单位级":
                company = "C";
                break;
            case "班组级":
                company = "D";
                break;
        }
        String removeJC = taskManagementDto.getCheckType().replace("检查", "");
        String resultcheckType = toPinyin.ToFirstChar(removeJC);

        String orderCode = company + resultcheckType.toUpperCase() + "%" + time;
        String front = company + resultcheckType.toUpperCase();
        String code = taskDao.queryOrderCode2(orderCode);
        if (code == null) {
            code = "01";
        } else {
            String s = code.replace(front, "");
            String s1 = s.replace("-" + time, "");
            code = sortCodeUtil.getMaxCodeString(s1);
        }
        String resultCode = company + resultcheckType.toUpperCase() + code + "-" + time;
        taskManagementDto.setOrderNumber(resultCode);
        if (taskDao.addTask(taskManagementDto) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String deleteTask(Integer id) {
        if (taskDao.deleteTask(id) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional
    //未通过
    public String editTask(TaskManagementDto taskManagementDto, int userId) {
        String status = taskManagementDto.getStatus();
        switch (status) {
            case "已下达": {
                int i = taskDao.updateTask(taskManagementDto);
                if (i <= 0)
                    throw new WLHSException("更新失败");
                String CheckPerosnsId = taskManagementDto.getLeaderIDs();
                taskCheckPersonsPojo.setStatus(taskManagementDto.getStatus());
                taskCheckPersonsPojo.setTaskID(taskManagementDto.getTaskID());
                for (String id : CheckPerosnsId.split(",")) {
                    taskCheckPersonsPojo.setCheckPersonsID(id);
                    taskDao.addTaskCheckPersonsPojo(taskCheckPersonsPojo);
                }

                //发信息
                TaskManagementDto taskManagementDto1 = taskDao.queryTasksByID(taskManagementDto.getTaskID(), null, null, null, null);
                String[] split = taskManagementDto1.getLeaderIDs().split(",");
                for (String aSplit : split) {
                    Mail mail = sendMessageUtil.getMail(CodeDict.SEND_TASK, userId, Integer.parseInt(aSplit), taskManagementDto1.getOrderNumber());
                    sendMessageUtil.sendMessage(mail);
                }
                return NR.r();
            }
            case "执行中":
                int flag = taskDao.updateTaskCheckPersonsStatus(Integer.parseInt(taskManagementDto.getTaskCheckPersonsID()), taskManagementDto.getStatus(), taskManagementDto.getTaskID());
                if (flag <= 0)
                    throw new WLHSException("更新失败");
                if (taskDao.updateTask(taskManagementDto) <= 0)
                    throw new WLHSException("更新失败");
                return NR.r();
            default: {
                if (taskDao.updateTask(taskManagementDto) <= 0)
                    throw new WLHSException("更新失败");
                return NR.r();
            }
        }
    }

    @Override
    public String listTaskByCondition(String issueDate1, String issueDate2, String status, int pageIdx, int pageSize, String type, String isOrderBy, Integer leaderID, Integer publishID, String currentDays, String exceptStatus) {
        if (StringUtils.isNotBlank(issueDate1) && StringUtils.isBlank(issueDate2)) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            issueDate2 = df.format(new Date());// new Date()为获取当前系统时间
        }
        if (null != taskDao.queryTasksByCondition(issueDate1, issueDate2, status, isOrderBy, leaderID, publishID, currentDays, exceptStatus, url)) {
            if (type.equals("all")) {
                List<TaskManagementDto> list = taskDao.queryTasksByCondition(issueDate1, issueDate2, status, isOrderBy, leaderID, publishID, currentDays, exceptStatus, url);
                List<TaskManagementDto> newList = getNamesUtil.changeEmployeeCodeToNames(list);
                return NR.r(newList);
            }
            int total = taskDao.queryTotal(issueDate1, issueDate2, status, isOrderBy, leaderID, publishID, currentDays, exceptStatus);
            PageHelper.startPage(pageIdx, pageSize);
            List<TaskManagementDto> list = taskDao.queryTasksByCondition(issueDate1, issueDate2, status, isOrderBy, leaderID, publishID, currentDays, exceptStatus, url);
            List<TaskManagementDto> newList = getNamesUtil.changeEmployeeCodeToNames(list);
            return NR.r(newList, total, pageIdx);

        } else
            throw new WLHSException("查询结果为空");
    }

    @Override
    public String listTaskByID(int id, String isOrderBy, Integer leaderID, Integer publishID) {
        return NR.r(taskDao.queryTasksByID(id, isOrderBy, leaderID, publishID, url));
    }

    @Override
    public String queryTasksByPublishPerson(TaskManagementDto taskManagementDto) {
        if (null == taskDao.queryTasksByPublishPerson(taskManagementDto.getCheckPersonsID(), taskManagementDto.getStatus(), taskManagementDto.getIsOrderBy(), taskManagementDto.getIssueDate1(), taskManagementDto.getIssueDate2(), url))
            throw new WLHSException("查询失败");
        if (taskManagementDto.getType().equals("all")) {
            List<TaskManagementDto> list = taskDao.queryTasksByPublishPerson(taskManagementDto.getCheckPersonsID(), taskManagementDto.getStatus(), taskManagementDto.getIsOrderBy(), taskManagementDto.getIssueDate1(), taskManagementDto.getIssueDate2(), url);
            return NR.r(list);
        }
        int list_total = taskDao.queryTotalTasksByPublishPerson(taskManagementDto.getCheckPersonsID(), taskManagementDto.getStatus(), taskManagementDto.getIsOrderBy(), taskManagementDto.getIssueDate1(), taskManagementDto.getIssueDate2());
        PageHelper.startPage(taskManagementDto.getPageIdx(), taskManagementDto.getPageSize());
        List<TaskManagementDto> list = taskDao.queryTasksByPublishPerson(taskManagementDto.getCheckPersonsID(), taskManagementDto.getStatus(), taskManagementDto.getIsOrderBy(), taskManagementDto.getIssueDate1(), taskManagementDto.getIssueDate2(), url);
        return NR.r(CodeDict.CODE_MESSAGE_DATA_PAGE_LIST, 0, 0, null, list, list_total, taskManagementDto.getPageIdx());
    }

    @Override
    public String queryTasksByPublishPersonByID(int id) {
        taskManagementDto = taskDao.queryTasksByPublishPersonByID(id, url);
        if (null != taskDao.queryTasksByPublishPersonByID(id, url)) {
            return NR.r(CodeDict.CODE_MESSAGE_DATA, 0, CodeDict.SELECT_FAILE, taskManagementDto, null, 0, 0);
        } else {
            return NR.r(CodeDict.CODE_MESSAGE_DATA, -1, CodeDict.SELECT_FAILE, null, null, 0, 0);
        }
    }
}
